package com.mby.controller;

import com.mby.entity.*;
import com.mby.entity.User;
import com.mby.service.IPushService;
import com.mby.service.IRongYunService;
import com.mby.utils.*;
import io.rong.RongCloud;
import io.rong.messages.BaseMessage;
import io.rong.messages.CustomTxtMessage;
import io.rong.messages.TxtMessage;
import io.rong.models.*;
import io.rong.models.Result;
import io.rong.models.chatroom.ChatroomModel;
import io.rong.models.group.GroupMember;
import io.rong.models.group.GroupModel;
import io.rong.models.message.ChatroomMessage;
import io.rong.models.message.GroupMessage;
import io.rong.models.message.SystemMessage;
import io.rong.models.response.GroupUser;
import io.rong.models.response.GroupUserQueryResult;
import io.rong.models.response.TokenResult;
import io.rong.models.user.UserModel;
import net.dongliu.requests.Header;
import net.dongliu.requests.Requests;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by noah on 2018/5/2.
 */
@RestController
public class RongCloudController extends BaseController{

    @Resource
    private IPushService pushService;

    @Resource
    private IRongYunService rongYunService;

    /**
     * 验证当前预检单是否已经创建了直播间
     */
    @GetMapping(value = "/precheck/{precheck_id}/groups")
    private void getPrecheckGroup(@PathVariable Integer precheck_id) throws Exception{
        ChatGroup chatGroup = mongoTool.findOne("","{'id':"+precheck_id+"}",ChatGroup.class);
        if(chatGroup != null){
            respData(chatGroup);
        }else{
            respData(0);
        }
    }

    /**
     * 创建群组
     * @param chatGroup
     * @throws Exception
     */
    @PostMapping(value = "/groups", produces = "application/json; charset=UTF-8")
    private void createGroup(@RequestBody ChatGroup chatGroup) throws Exception{
        long count = mongoTool.count("{'id':" + chatGroup.getId() + "}", ChatGroup.class);
        if (count == 0) {
            int s = 0;
            List<?> users = mongoTool.findMany("{'dealerId':'" + chatGroup.getDealerId() + "'}", "", User.class);
            if (users.size() > 0) {
                User customer = CsAppUtil.getUserInfo(chatGroup.getVin());
                if (customer == null) {
                    respErr("No Vehicle");
                } else {
                    String customerId = "C" + customer.getId(); //需要把车主id跟dms用户id防止冲突
                    User user;Set<String> ids = new HashSet<>();
                    //10061017 售后经理、10061022 车间主管、10061025 前台主管
                    for (int i = 0; i < users.size(); i++) {
                        user = (User) users.get(i);
                        if (user.getRoleIds() != null) {
                            if (user.getRoleIds().indexOf("10061017")>=0|| user.getRoleIds().indexOf("10061022")>=0 || user.getRoleIds().indexOf("10061025")>=0) {
                                ids.add(user.getId().toString());
                            }
                        }
                    }
                    //创建者
                    ids.add(chatGroup.getCreatedBy().toString());

                    GroupMember[] members = new GroupMember[ids.size()];
                    GroupMember groupMember;
                    int i = 0;
                    for(String id : ids){
                        groupMember = new GroupMember();
                        groupMember.setId(id);
                        members[i] = groupMember;
                        i++;
                    }
                    GroupModel groupModel = new GroupModel()
                            .setId(chatGroup.getId().toString())
                            .setMembers(members)
                            .setName(chatGroup.getPlateNo());
                    Result result = rongCloud.group.create(groupModel);
                    if (result.getCode() == 200) {
                        chatGroup.setArrivedDate(new Date(chatGroup.getArrivedAt() * 1000));
                        chatGroup.setArrivedAt(chatGroup.getArrivedAt() * 1000);
                        chatGroup.setCreatedAt(new Date());
                        chatGroup.setCustomerId(customerId);
                        chatGroup.setBrandId(customer.getBrandId());
                        chatGroup.setEst15(0);
                        chatGroup.setStatus2(0);
                        chatGroup.setChecked40(0);
                        mongoTool.addOne(chatGroup);
                        importMembers(groupModel);
                        String token = loginRongCloud(customerId,"车主","https://car-pics.themobiyun.com/csapp20/avatars/"+customer.getId()+"?"+new Date().getTime());
                        pushService.sendCSWelPush(chatGroup.getId());
                        sendCsMessage(chatGroup.getId(),customerId,customer.getBrandId(),chatGroup.getDealerId(),token,"wel");
                        respData(chatGroup);
                    } else {
                        respErr("RongCloud Err " + result.getCode());
                    }
                }
            } else {
                respErr("No Users");
            }
        } else {
            respErr("GroupId Existent");
        }
    }

    private void sendCsMessage(Integer groupId,String userId,Integer brand_id,String dealer_id,String token,String type) throws Exception{
        Map<String,Object> param = new HashMap<>();
        param.put("group","car");
        param.put("type",10);
        param.put("rule",4);
        if("wel".equals(type)){
            param.put("title",WebConstant.CS_LIVE_START_TITLE);
            param.put("content",WebConstant.CS_LIVE_START_CONTENT);
        }else{
            param.put("title",WebConstant.CS_LIVE_END_TITLE);
            param.put("content",WebConstant.CS_LIVE_END_CONTENT);
        }
        param.put("start_on",new Date().getTime()/1000);
        param.put("end_on",getAddedDate(new Date(),30).getTime()/1000);
        param.put("source_type","DEALER");
        param.put("user_id",userId.replace("C",""));
        param.put("brand_id",brand_id);
        param.put("dealer_id",CsAppUtil.getDealer(dealer_id).getIntId());
        param.put("dealer_name",CsAppUtil.getDealer(dealer_id).getName());
        param.put("token",token);
        param.put("in_card",true);
        param.put("in_center",true);
        param.put("entity_id",groupId);
        param.put("created_at",new Date().getTime()/1000);
        param.put("top",true);
        String result = Requests.post(WebConstant.CS_MSG_URL)
                .headers(new Header("content-type","application/json;charset=UTF-8"))
                .verify(false)
                .body(com.alibaba.fastjson.JSON.toJSONString(param))
                .send().readToText();
        System.out.println(result);
    }

    private void importMembers(GroupModel groupModel){
        GroupMember[] members = groupModel.getMembers();
        if(members.length > 0){
            String groupId = groupModel.getId();
            GroupMember groupMember; String userId; ChatGroupMember chatGroupMember;
            for(int i=0;i<members.length;i++){
                chatGroupMember = new ChatGroupMember();
                groupMember = members[i];
                userId = groupMember.getId();
                chatGroupMember.setGroupId(Integer.parseInt(groupId));
                chatGroupMember.setUserId(userId);
                chatGroupMember.setId(mongoTool.getAutoIncreaseID(chatGroupMember.getClass().getName()));
                mongoTool.addOne(chatGroupMember);
            }
        }
    }

    private void sendGroupMessage(Integer groupId,Integer senderId,String dealerId,String type,Integer vhc_id) throws Exception{
        try{
            WelcomeWords welcomeWords = mongoTool.findOne("", "{'dealerId':'" + dealerId + "'}", WelcomeWords.class);
            RongUser rongUser = new RongUser();
            String portrait;
            if (welcomeWords != null) {
                if("wel".equals(type)){ //欢迎语
                    long count = mongoTool.count("{'id':"+groupId+",'weledAt':null}",ChatGroup.class);
                    if (welcomeWords.getWelcomeWords() != null && !"".equals(welcomeWords.getWelcomeWords()) && count > 0) {
                        User user = mongoTool.findOne("userName,id,avatarVer,roleName", "{'id':" + senderId + "}", User.class);
                        if(WebConstant.APP_ENV.equals("prod")){
                            portrait = "http://live-asset.themobiyun.com/userIcon/"+user.getId()+"?"+new Date().getTime();
                        }else{
                            portrait = "http://live-asset.themobiyun.com/userIcon/dev/"+user.getId()+"?"+new Date().getTime();
                        }
                        rongUser.setUserId(user.getId());
                        rongUser.setId(user.getId());
                        rongUser.setName(user.getUserName()+"（"+user.getRoleName().split(",")[0]+"）");
                        rongUser.setPlace(user.getRoleName());
                        rongUser.setPortrait(portrait);
                        rongUser.setUser(rongUser);
                        MbyMessage message = new MbyMessage(welcomeWords.getWelcomeWords(), "文本信息", rongUser);
                        GroupMessage  groupMessage = new GroupMessage()
                                .setSenderId(senderId.toString())
                                .setTargetId(groupId.toString().split(","))
                                .setContent(message)
                                .setPushContent(welcomeWords.getWelcomeWords())
                                .setIsIncludeSender(1);
                        rongCloud.message.group.send(groupMessage);
                        mongoTool.update("{'weledAt':'"+getNow()+"'}","{'id':"+groupId+"}",ChatGroup.class);
                    }
                }else if("over".equals(type)){ //结束语
                    if (welcomeWords.getOverWords() != null && !"".equals(welcomeWords.getOverWords())) {
                        if(WebConstant.APP_ENV.equals("prod")){
                            portrait = "http://live-asset.themobiyun.com/userIcon/"+currentUser().getId()+"?"+new Date().getTime();
                        }else{
                            portrait = "http://live-asset.themobiyun.com/userIcon/dev/"+currentUser().getId()+"?"+new Date().getTime();
                        }
                        rongUser.setUserId(currentUser().getId());
                        rongUser.setId(currentUser().getId());
                        rongUser.setName(currentUser().getUserName()+"（"+currentUser().getRoleName().split(",")[0]+"）");
                        rongUser.setPlace(currentUser().getRoleName());
                        rongUser.setPortrait(portrait);
                        rongUser.setUser(rongUser);
                        MbyMessage message = new MbyMessage(welcomeWords.getOverWords(), "文本信息", rongUser);
                        GroupMessage groupMessage = new GroupMessage()
                                .setSenderId(senderId.toString())
                                .setTargetId(groupId.toString().split(","))
                                .setContent(message)
                                .setPushContent(welcomeWords.getOverWords())
                                .setIsIncludeSender(1);
                        rongCloud.message.group.send(groupMessage);
                    }
                }
            }

            if("health".equals(type)){ //车辆健康卡
                User user = mongoTool.findOne("userName,id,avatarVer,roleName", "{'id':" + senderId + "}", User.class);
                if(WebConstant.APP_ENV.equals("prod")){
                    portrait = "http://live-asset.themobiyun.com/userIcon/"+user.getId()+"?"+new Date().getTime();
                }else{
                    portrait = "http://live-asset.themobiyun.com/userIcon/dev/"+user.getId()+"?"+new Date().getTime();
                }
                rongUser.setUserId(user.getId());
                rongUser.setId(user.getId());
                rongUser.setName(user.getUserName()+"（"+user.getRoleName().split(",")[0]+"）");
                rongUser.setPlace(user.getRoleName());
                rongUser.setPortrait(portrait);
                rongUser.setUser(rongUser);
                HealthMessage message = new HealthMessage(vhc_id.toString(), "health", rongUser);
                System.out.println("******************************************");
                System.out.println("车辆健康卡发送者的头像："+portrait);
                System.out.println("车辆健康卡发送者的名称："+user.getUserName()+"（"+user.getRoleName().split(",")[0]+"）");
                System.out.println("******************************************");
                GroupMessage groupMessage = new GroupMessage()
                    .setSenderId(senderId.toString())
                    .setTargetId(groupId.toString().split(","))
                    .setObjectName("MBY:HealthMsg")
                    .setContent(message)
                    .setIsIncludeSender(1);
                rongCloud.message.group.send(groupMessage);
                mongoTool.update("{'healthedAt':'"+getNow()+"'}","{'id':"+groupId+"}",ChatGroup.class);
            }else if("card".equals(type)){ //名片
                if(WebConstant.APP_ENV.equals("prod")){
                    portrait = "http://live-asset.themobiyun.com/userIcon/"+currentUser().getId()+"?"+new Date().getTime();
                }else{
                    portrait = "http://live-asset.themobiyun.com/userIcon/dev/"+currentUser().getId()+"?"+new Date().getTime();
                }
                rongUser.setDealerId(CsAppUtil.getDealer(currentUser().getDealerId()).getIntId());
                rongUser.setDealerName(CsAppUtil.getDealer(currentUser().getDealerId()).getName());
                rongUser.setId(currentUser().getId());
                rongUser.setName(currentUser().getUserName());
                rongUser.setPhone(currentUser().getPhone());
                rongUser.setPlace(currentUser().getRoleName());
                rongUser.setPortrait(portrait);
                rongUser.setUserId(currentUser().getId());
                rongUser.setUser(rongUser);
                CardMessage message = new CardMessage(com.alibaba.fastjson.JSON.toJSONString(rongUser), "card", rongUser);
                GroupMessage groupMessage = new GroupMessage()
                        .setSenderId(senderId.toString())
                        .setTargetId(groupId.toString().split(","))
                        .setObjectName("MBY:CardMsg")
                        .setContent(message)
                        .setIsIncludeSender(1);
                rongCloud.message.group.send(groupMessage);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 发送车辆健康卡消息
     * POST /groups/health_card_msg?precheck_id=1232&vhc_id=1232
     * @param vhc_id
     */
    @PostMapping(value = "/groups/health_card_msg")
    private void sendCardMsg(Integer precheck_id,Integer vhc_id) throws Exception{
        ChatGroup chatGroup = mongoTool.findOne("","{'id':"+precheck_id+",'deletedAt':null}",ChatGroup.class);
        if(chatGroup != null){
            mongoTool.update("{'vhcId':"+vhc_id+"}","{'id':"+chatGroup.getId()+"}",ChatGroup.class);
            long count = mongoTool.count("{'userId':'"+chatGroup.getCustomerId()+"','groupId':"+chatGroup.getId()+"}",ChatGroupMember.class);
            if(count > 0){ //车主已经进群了
                sendGroupMessage(precheck_id,chatGroup.getCreatedBy(),chatGroup.getDealerId(),"health",vhc_id);
            }
            respData(ok);
        }else{
            respErr("Group Dismissed Or Not Existent");
        }
    }

    /**
     * 解散群组
     * DELETE /groups/{groupId}
     * @param groupId
     * @throws Exception
     */
    @DeleteMapping(value = "/groups/{groupId}")
    private void deleteGroups(@PathVariable Integer groupId) throws Exception{
        ChatGroup chatGroup = mongoTool.findOne("","{'id':"+groupId+",'deletedAt':null}",ChatGroup.class);
        if(chatGroup != null){
            if(!chatGroup.getCreatedBy().equals(currentUser().getId())){
                respErr("Not Creater");
            }else{
                GroupMember[] members = new GroupMember[]{new GroupMember().setId(currentUser().getId().toString())};
                GroupModel groupModel = new GroupModel().setId(groupId.toString()).setMembers(members);
                sendGroupMessage(groupId,currentUser().getId(),currentUser().getDealerId(),"over",null);
                sendGroupMessage(chatGroup.getId(), chatGroup.getCreatedBy(), chatGroup.getDealerId(), "card",null);
                Result result = rongCloud.group.dismiss(groupModel);
                if(result.getCode() == 200){
                    mongoTool.update("{'deletedAt':'"+getNow()+"'}","{'id':"+groupId+"}",ChatGroup.class);
                    mongoTool.delete("{'groupId':"+groupId+"}",ChatGroupMember.class);
                    pushService.sendCSOverPush(groupId);
                    //sendCsMessage(chatGroup.getId(),chatGroup.getCustomerId(),chatGroup.getBrandId(),chatGroup.getDealerId(),null,"over");
                    respData(ok);
                }else{
                    respErr("RongCloud Err "+result.getCode());
                }
            }
        }else{
            respErr("Group Dismissed Or Not Existent");
        }
    }

    /**
     * 用户加入群组
     * POST /groups/{groupId}/members
     * @param groupId
     * @param chatGroup
     */
    @PostMapping(value = "/groups/{groupId}/members")
    private void joinGroup(@PathVariable Integer groupId,@RequestBody ChatGroup chatGroup) throws Exception{
        ChatGroup cg = mongoTool.findOne("","{'id':"+groupId+",'deletedAt':null}",ChatGroup.class);
        if(cg == null){
            respErr("Group Dismissed Or Not Existent");
        }else{
            if(!cg.getCreatedBy().equals(currentUser().getId())){
                respErr("Not Creater");
            }else{
                String[] members = chatGroup.getMembers();
                if(members.length > 0){
                    long count;
                    GroupMember[] groupMembers = new GroupMember[members.length];
                    for(int i=0;i<members.length;i++){
                        count = mongoTool.count("{'id':"+Integer.parseInt(members[i])+",'dealerId':'"+currentUser().getDealerId()+"'}",User.class);
                        if(count == 0){
                            respErr("User Not Existent");
                        }else{
                            GroupMember groupMember = new GroupMember();
                            groupMember.setId(members[i]);
                            groupMembers[i] = groupMember;
                        }
                    }
                    GroupModel groupModel = new GroupModel().setId(groupId.toString()).setMembers(groupMembers).setName(cg.getPlateNo());
                    Result result = rongCloud.group.join(groupModel);
                    if(result.getCode() == 200){
                        joinCustomer(groupModel);
                        respData(ok);
                    }else{
                        respErr("RongCloud Err "+result.getCode());
                    }
                }else{
                    respErr("No Users");
                }
            }
        }
    }

    /**
     * 工单派工完成以后技师加入群组,车主用户加入群聊
     * POST /groups/mechanics?precheck_id=1232
     * @param precheck_id
     * @param chatGroup
     */
    @PostMapping(value = "/groups/mechanics")
    private void mechanicsjoinGroup(Integer precheck_id,@RequestBody ChatGroup chatGroup) throws Exception{
        String customerId = null;
        ChatGroup cg = mongoTool.findOne("","{'id':"+precheck_id+",'deletedAt':null}",ChatGroup.class);
        User user; String portrait; String userId; boolean flag = false;
        if(cg == null){
            respErr("Group Dismissed Or Not Existent");
        }else{
            String[] members = chatGroup.getMembers();
            if(members.length > 0){
                long count;
                GroupMember[] groupMembers = new GroupMember[members.length];
                for(int i=0;i<members.length;i++){
                    GroupMember groupMember = new GroupMember();
                    userId = members[i];
                    if(members[i].indexOf("C") >= 0){ //车主用户
                        customerId = members[i];
                    }else{
                        flag = true;
                        user = mongoTool.findOne("","{'id':"+userId+"}",User.class);
                        if(user != null){
                            if(WebConstant.APP_ENV.equals("prod")){
                                portrait = "http://live-asset.themobiyun.com/userIcon/"+user.getId().toString()+"?"+new Date().getTime();
                            }else{
                                portrait = "http://live-asset.themobiyun.com/userIcon/dev/"+user.getId().toString()+"?"+new Date().getTime();
                            }
                            loginRongCloud(members[i],user.getUserName()+"（"+user.getRoleName().split(",")[0]+"）",portrait);
                        }
                    }
                    groupMember.setId(members[i]);
                    groupMembers[i] = groupMember;
                }
                GroupModel groupModel = new GroupModel().setId(precheck_id.toString()).setMembers(groupMembers).setName(cg.getPlateNo());
                Result result = rongCloud.group.join(groupModel);
                if(result.getCode() == 200){
                    if(flag && cg.getStatus2() == 0){
                        pushService.sentStatusPush(cg);
                        rongYunService.sentStatusMsg(cg,2);
                        mongoTool.update("{'status2':1,'maintainedAt':'"+getNow()+"'}","{'id':"+cg.getId()+"}",ChatGroup.class);
                    }
                    joinCustomer(groupModel);
                    if(customerId != null){ //车主用户发送欢迎语
                        sendGroupMessage(cg.getId(), cg.getCreatedBy(), cg.getDealerId(), "wel",null);
                        if(cg.getHealthedAt() == null && cg.getVhcId() != null){
                            sendGroupMessage(precheck_id,cg.getCreatedBy(),cg.getDealerId(),"health",cg.getVhcId());
                        }
                    }
                    respData(ok);
                }else{
                    respErr("RongCloud Err "+result.getCode());
                }
            }else{
                respErr("No Users");
            }
        }
    }

    private void joinCustomer(GroupModel groupModel) throws Exception{
        GroupMember[] members = groupModel.getMembers();
        if(members.length > 0){
            String groupId = groupModel.getId();
            GroupMember groupMember; String userId; ChatGroupMember chatGroupMember; long count;
            for(int i=0;i<members.length;i++){
                chatGroupMember = new ChatGroupMember();
                groupMember = members[i];
                userId = groupMember.getId();
                chatGroupMember.setGroupId(Integer.parseInt(groupId));
                chatGroupMember.setUserId(userId);
                chatGroupMember.setId(mongoTool.getAutoIncreaseID(chatGroupMember.getClass().getName()));
                count = mongoTool.count("{'groupId':"+groupId+",'userId':'"+userId+"'}",ChatGroupMember.class);
                if(count == 0){
                    mongoTool.addOne(chatGroupMember);
                }
            }
        }
    }

    /**
     * 把群组成员踢出群
     * PUT /groups/{groupId}/members
     * @param groupId
     * @param chatGroup
     * @throws Exception
     */
    @PutMapping(value = "/groups/{groupId}/members")
    private void quitGroup(@PathVariable Integer groupId,@RequestBody ChatGroup chatGroup) throws Exception{
        ChatGroup cg = mongoTool.findOne("","{'id':"+groupId+",'deletedAt':null}",ChatGroup.class);
        if(cg == null){
            respErr("Group Dismissed Or Not Existent");
        }else{
            if(!cg.getCreatedBy().equals(currentUser().getId())){
                respErr("Not Creater");
            }else{
                String[] members = chatGroup.getMembers();
                if(members.length > 0){
                    long count;
                    GroupMember[] groupMembers = new GroupMember[members.length];
                    for(int i=0;i<members.length;i++){
                        count = mongoTool.count("{'id':"+Integer.parseInt(members[i])+",'dealerId':'"+currentUser().getDealerId()+"'}",User.class);
                        if(count == 0){
                            respErr("User Not Existent");
                        }else{
                            GroupMember groupMember = new GroupMember();
                            groupMember.setId(members[i]);
                            groupMembers[i] = groupMember;
                        }
                    }
                    GroupModel groupModel = new GroupModel().setId(groupId.toString()).setMembers(groupMembers).setName(cg.getPlateNo());
                    Result result = rongCloud.group.quit(groupModel);
                    if(result.getCode() == 200){
                        quitCustomer(groupModel);
                        respData(ok);
                    }else{
                        respErr("RongCloud Err "+result.getCode());
                    }
                }else{
                    respErr("No Users");
                }
            }
        }
    }

    private void quitCustomer(GroupModel groupModel) throws Exception{
        GroupMember[] members = groupModel.getMembers();
        if(members.length > 0){
            String groupId = groupModel.getId();
            GroupMember groupMember; String userId; ChatGroupMember chatGroupMember;
            for(int i=0;i<members.length;i++){
                chatGroupMember = new ChatGroupMember();
                groupMember = members[i];
                userId = groupMember.getId();
                mongoTool.delete("{'groupId':"+groupId+",'userId':'"+userId+"'}",ChatGroupMember.class);
            }
        }
    }

    /**
     * 获取群组的用户列表
     * @param groupId
     * @throws Exception
     */
    @GetMapping(value = "/groups/{groupId}/members")
    private void getGroupMembers(@PathVariable Integer groupId) throws Exception{
        ChatGroup group = mongoTool.findOne("","{'id':"+groupId+",'deletedAt':null}",ChatGroup.class);
        if(group == null){
            respErr("Group Dismissed Or Not Existent");
        }else{
            GroupModel groupModel = new GroupModel().setId(groupId.toString());
            GroupUserQueryResult result = rongCloud.group.get(groupModel);
            if(result.getMembers().size() > 0){
                String userIds = ""; String customer = "";
                List<GroupUser> members = result.getMembers();
                GroupUser groupUser;
                for(int i=0;i<members.size();i++){
                    groupUser = members.get(i);
                    if(groupUser.getId().contains("C")){
                        customer = groupUser.getId();
                    }else{
                        userIds = userIds + groupUser.getId() + ",";
                    }
                }
                resultMap.put("users",mongoTool.findMany("userName,phone,roleName,quited,roleIds,avatarVer,status","{'id#':'"+userIds+"','quited':false}","",User.class));
                resultMap.put("customer",customer.replace("C",""));
                resultMap.put("owner",group.getCreatedBy());
                respData(resultMap);
            }
        }
    }

    /**
     * 获取群组的用户列表
     * GET /groups/members?groupId=70000
     * @param groupId
     * @throws Exception
     */
    @GetMapping(value = "/groups/members")
    private void getGroupMembersWithOutLogin(Integer groupId) throws Exception{
        ChatGroup group = mongoTool.findOne("","{'id':"+groupId+",'deletedAt':null}",ChatGroup.class);
        if(group == null){
            respErr("Group Dismissed Or Not Existent");
        }else{
            GroupModel groupModel = new GroupModel().setId(groupId.toString());
            GroupUserQueryResult result = rongCloud.group.get(groupModel);
            if(result.getMembers().size() > 0){
                String userIds = ""; String customer = "";
                List<GroupUser> members = result.getMembers();
                GroupUser groupUser;
                for(int i=0;i<members.size();i++){
                    groupUser = members.get(i);
                    if(groupUser.getId().contains("C")){
                        customer = groupUser.getId();
                    }else{
                        userIds = userIds + groupUser.getId() + ",";
                    }
                }
                resultMap.put("users",mongoTool.findMany("userName,phone,roleName,quited,roleIds,avatarVer,status","{'id#':'"+userIds+"','quited':false}","",User.class));
                resultMap.put("customer",customer.replace("C",""));
                resultMap.put("owner",group.getCreatedBy());
                respData(resultMap);
            }
        }
    }

    /**
     * 获取用户所在的群组列表
     * GET /users/{userId}/groups?group_id=22
     * @param userId
     * @throws Exception
     */
    @GetMapping(value = "/users/{userId}/groups")
    private void getGroups(@PathVariable Integer userId,Integer group_id) throws Exception{
        String group_id_str = "";
        if(group_id != null){
            group_id_str = "'groupId':"+group_id+",";
        }
        List<?> list = mongoTool.findMany("groupId","{"+group_id_str+"'userId':'"+userId+"'}","",ChatGroupMember.class);
        ChatGroupMember chatGroupMember; String groupIds = "";
        for(int i=0;i<list.size();i++){
            chatGroupMember = (ChatGroupMember)list.get(i);
            groupIds = groupIds + chatGroupMember.getGroupId() + ",";
        }
        respData(mongoTool.findMany("{'id#':'"+groupIds+"','deletedAt':null}","createdAt desc",ChatGroup.class));
    }

    /**
     * 获取车主最近一次接待的sa信息、
     * GET /customers/last_sa?user_id=10000002&brand_id=1&dealer_id=233
     * @throws Exception
     */
    @GetMapping(value = "/customers/last_sa")
    private void getLastSa(Integer user_id,Integer brand_id,Integer dealer_id) throws Exception{
        List<?> list = mongoTool.findMany("","{'customerId':'C"+user_id+"','brandId':"+brand_id+",'dealerId':'"+CsAppUtil.getDealer(dealer_id).getId()+"'}","created_at",ChatGroup.class);
        if(list != null && list.size() > 0){
            ChatGroup lastGroup = (ChatGroup)list.get(list.size()-1);
            if(lastGroup != null){
                Integer sa = lastGroup.getCreatedBy();
                respData(mongoTool.findOne("","{'id':"+sa+"}",User.class));
            }else{
                respData(ok);
            }
        }else{
            respData(ok);
        }
    }

    /**
     * 获取经销商所有未在群组的用户
     * get /live/users_for_add?group_id=2810
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/users_for_add")
    public void getUsersForAdd(Integer group_id) throws Exception{
        List<?> list = mongoTool.findMany("","{'groupId':"+group_id+"}","",ChatGroupMember.class);
        ChatGroupMember cgm; Set<String> groupUsers = new HashSet<>(); List<User> result = new ArrayList<>();
        for(int i=0;i<list.size();i++){
            cgm = (ChatGroupMember)list.get(i);
            groupUsers.add(cgm.getUserId());
        }
        list = mongoTool.findMany("","{'dealerId':'"+currentUser().getDealerId()+"',}","", User.class);
        User user;
        for(int i=0;i<list.size();i++){
            user = (User)list.get(i);
            if(!groupUsers.contains(user.getId().toString())){
                if(user.getRongCloudToken() != null){
                    user.setStatus(1);
                }else{
                    user.setStatus(0);
                }
                if(user.getAvatarVer() == null){
                    user.setAvatarVer(0);
                }
                result.add(user);
            }
        }
        respData(result);
    }

    /**
     * 获取聊天室状态
     * GET /live/groups/status?group_id=2810
     */
    @GetMapping(value = "/groups/status")
    private void getGroupStatus(Integer group_id) throws Exception{
        long count = mongoTool.count("{'id':"+group_id+",'deletedAt':null}",ChatGroup.class);
        if(count == 0){
            respData("closed");
        }else{
            respData("open");
        }
    }

    /**
     * 获取当前用户是否在群里
     * GET /live/groups/isin?group_id=2810
     */
    @GetMapping(value = "/groups/isin")
    private void getGroupIsin(Integer group_id) throws Exception{
        long count = mongoTool.count("{'id':"+group_id+",'deletedAt':null}",ChatGroup.class);
        if(count == 0){
            respData("closed");
        }else{
            count = mongoTool.count("{'groupId':"+group_id+",'userId':'"+currentUser().getId()+"'}",ChatGroupMember.class);
            if(count > 0){
                respData("in");
            }else{
                respData("out");
            }
        }
    }
}
